import React, { useState, useEffect } from 'react';
// @ts-ignore
import { TjTable } from '@/pages/ETrade/components';
import _ from 'lodash';
import { useTablePipeline, features } from 'ali-react-table';
import type { ArtColumn, SortItem } from 'ali-react-table';

const getColumns = (columsValue: ILeftTableProps['tableHead']): ArtColumn[] => {
  const columns: ArtColumn[] = [];

  if (columsValue && columsValue.length > 0) {
    // 添加表格第一列标题
    columns.push({
      name: '交易单元',
      align: 'left',
      code: 'name',
      width: 120,
      lock: true,
    });

    const parentNames = Object.keys(_.groupBy(columsValue, 'parentName'));
    parentNames.map((item) => {
      columns.push({
        name: item,
        align: 'center',
        children: [],
      });
    });

    columns.map((colItem, index) => {
      const children: ArtColumn[] = [];
      columsValue.map((item) => {
        if (colItem.name == item.parentName) {
          children.push({
            name: item.name,
            align: 'center',
            width: 100,
            code: item.field,
            features: { sortable: true },
            render: (value) => value ?? '-',
          });
        }
      });
      columns[index].children = children;
    });
  }

  return columns;
};

const removeEmptyRowData = (dataSource: any[], name: string) => {
  const sortData: any[] = [];
  const noSortData: any[] = [];

  dataSource.map((item) => {
    if (item[name] || item[name] == 0) {
      sortData.push(item);
    } else {
      noSortData.push(item);
    }
  });
  return {
    noSortData,
    sortData,
  };
};

const LeftTable: React.FC<ILeftTableProps> = (props) => {
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [openKeys, onChangeOpenKeys] = useState<string[]>([]);
  const [sorts, setSorts] = useState<SortItem[]>([]);

  useEffect(() => {
    if (_.isArray(props.tableData)) {
      setDataSource(props.tableData);
    }
  }, [props.tableData]);

  const pipeline = useTablePipeline({ components: {} })
    .input({ dataSource, columns: getColumns(props.tableHead) })
    .primaryKey('id')
    .use(
      features.treeMode({
        openKeys,
        onChangeOpenKeys,
        indentSize: 20,
      }),
    )
    .use(
      features.sort({
        mode: 'single',
        sorts,
        keepDataSource: true,
        onChangeSorts: (params: SortItem[]) => {
          setSorts(params);
          if (params.length) {
            const _dataSource = _.cloneDeep(props.tableData);
            const total = _dataSource[0];
            const spliceData = _dataSource.splice(1);
            const { sortData, noSortData } = removeEmptyRowData(spliceData, params[0].code);

            let newDataSource = [];
            newDataSource = sortData.sort((a, b) => {
              return params[0].order === 'desc'
                ? b[params[0].code] - a[params[0].code]
                : a[params[0].code] - b[params[0].code];
            });

            setDataSource([total, ...newDataSource, ...noSortData]);
            return;
          }

          setDataSource(props.tableData);
        },
        highlightColumnWhenActive: true,
      }),
    );

  return <TjTable {...pipeline.getProps()} isLoading={props.loading} />;
};

type headType = {
  field: string;
  name: string;
  parentName: string;
};

interface ILeftTableProps {
  tableHead: headType[];
  tableData: any[];
  loading?: boolean;
}

export default LeftTable;
